package com.okq.action;

import com.okq.action.base.BaseActionSupport;
import com.okq.entity.Approval;
import com.okq.entity.Product;
import com.okq.entity.Production;
import com.okq.entity.User;
import com.okq.service.*;
import com.okq.util.BaseTool;
import com.okq.util.Constant;
import com.okq.util.page.Page;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描述 : 产品action
 * 作者 : zdl
 * 日期 : 2017/7/15 15:55
 */
public class ProductAction extends BaseActionSupport {
    private static final long serialVersionUID = -5174139211154703045L;
    /**
     * 产品接口
     */
    @Autowired
    private IProductService productServiceImpl;
    /**
     * 生产接口
     */
    @Autowired
    private IProductionService productionServiceImpl;
    /**
     * 数据字典接口
     */
    @Autowired
    private IDictService dictServiceImpl;
    /**
     * 用户接口
     */
    @Autowired
    private IUserService userServiceImpl;
    /**
     * 审核接口
     */
    @Autowired
    private IApprovalService approvalServiceImpl;

    /**
     * 日志
     */
    private static final Logger logger = Logger.getLogger(ProductAction.class);
    /**
     * 分页开始条数
     */
    private int iDisplayStart;

    /**
     * 每页显示条数
     */
    private int iDisplayLength;

    private String id;
    private Product product;
    private String type;

    private String batch;
    private String productType;
    private String weldName;//焊接
    private String assembleName;//组装
    private String debugName;//调试
    private String checkName;//质检
    private String reason;//原因

    /**
     * 分页获取产品列表
     *
     * @return json
     */
    public String getProductList() {
        PrintWriter out = null;
        try {
            out = this.getResponse().getWriter();
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null) {
                if (iDisplayLength == 0) {
                    iDisplayLength = -1;
                }
                int pageNum = (int) (Math.ceil(iDisplayStart / iDisplayLength)) + 1;
                /* 分页信息 */
                Page<Product> pageInfo = new Page<>(iDisplayLength);
                pageInfo.setPageNo(pageNum);
                pageInfo = productServiceImpl.pageByProduct(pageInfo, product);
                int iTotalRecords = pageInfo.getTotalCount();
                int iTotalDisplayRecords = pageInfo.getTotalCount() < 0 ? 0 : pageInfo.getTotalCount();
                /* 得到结果 */
                List<Product> pList = pageInfo.getResult();
                /* 封装list */
                List<Map<String, Object>> pMapList = new ArrayList<>();
                if (pList != null && !pList.isEmpty() && pList.size() > 0) {
                    int i = (pageNum - 1) * iDisplayLength + 1;
                    for (Product p : pList) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("no", i);// 序号
                        map.put("id", p.getId());
                        String batch = "";
                        Production production = productionServiceImpl.getProductionById(p.getProductionId());
                        if (production != null) {
                            batch = StringUtils.defaultString(production.getBatch(), "");
                        }
                        map.put("batch", batch);
                        map.put("productTypeStr", dictServiceImpl.getDictByValueAndType(p.getProductType(), Constant.PRODUCT_TYPE));
                        map.put("code", StringUtils.defaultString(p.getCode(), ""));
                        map.put("name", StringUtils.defaultString(p.getName(), ""));
                        map.put("weldName", getUserNameById(p.getWeldId()));
                        map.put("assembleName", getUserNameById(p.getAssembleId()));
                        map.put("debugName", getUserNameById(p.getDebugId()));
                        map.put("checkName", getUserNameById(p.getCheckId()));
                        map.put("checkTime", StringUtils.defaultString(p.getCheckTime(), ""));
                        Integer checkResult = p.getCheckResult();
                        map.put("checkResult", checkResult);
                        String checkResultStr = "";
                        if (checkResult != null) {
                            switch (checkResult) {
                                case 0:
                                    checkResultStr = "未检测";
                                    break;
                                case 1:
                                    checkResultStr = "合格";
                                    break;
                                case 2:
                                    checkResultStr = "不合格";
                                    break;
                                default:
                                    break;
                            }
                        }
                        map.put("checkResultStr", checkResultStr);
                        Integer stockState = p.getStockState();
                        map.put("stockState", stockState);
                        String stockStateStr = "";
                        if (stockState != null) {
                            if (stockState == 0) {
                                stockStateStr = "入库";
                            } else if (stockState == 1) {
                                stockStateStr = "出库";
                            }
                        }
                        map.put("stockStateStr", stockStateStr);
                        map.put("outOrInTime", StringUtils.defaultString(p.getOutOrInTime(), ""));
                        pMapList.add(map);
                        i++;
                    }
                }
                Map<String, Object> jsonMap = new HashMap<>();
                jsonMap.put("iTotalRecords", iTotalRecords);
                jsonMap.put("iTotalDisplayRecords", iTotalDisplayRecords);
                jsonMap.put("aaData", pMapList);

                String json = BaseTool.toJson(jsonMap);
                out.print(json);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return null;
    }

    /**
     * 跳转
     *
     * @return 类型
     */
    public String toDetail() {
        try {
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null && StringUtils.isNotBlank(id)) {
                product = productServiceImpl.getProductById(id);
                if (product != null && type.equals("detail")) {
                    Production p = productionServiceImpl.getProductionById(product.getProductionId());
                    if (p != null) {
                        batch = StringUtils.defaultString(p.getBatch(), "");
                    }
                    productType = dictServiceImpl.getDictByValueAndType(p.getProductType(), Constant.PRODUCT_TYPE);
                    weldName = getUserNameById(product.getWeldId());
                    assembleName = getUserNameById(product.getAssembleId());
                    debugName = getUserNameById(product.getDebugId());
                    checkName = getUserNameById(product.getCheckId());
                    Approval a = approvalServiceImpl.getApprovalByTypeAndId(Constant.APPROVAL_CHECK, product.getId());
                    if (a != null && a.getResult() == 0) {
                        reason = StringUtils.defaultString(a.getReason(), "");
                    }
                    return "detail";
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
        return null;
    }

    /**
     * 根据用户ID获取用户名字
     *
     * @param userId 用户Id
     * @return name
     */
    private String getUserNameById(String userId) {
        if (StringUtils.isNotBlank(userId)) {
            User user = userServiceImpl.getUserById(userId);
            if (user != null) {
                return StringUtils.defaultString(user.getUserName(), "");
            }
        }
        return "";
    }

    public int getIDisplayStart() {
        return iDisplayStart;
    }

    public void setIDisplayStart(int iDisplayStart) {
        this.iDisplayStart = iDisplayStart;
    }

    public int getIDisplayLength() {
        return iDisplayLength;
    }

    public void setIDisplayLength(int iDisplayLength) {
        this.iDisplayLength = iDisplayLength;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public Product getProduct() {
        return product;
    }

    public void setProduct(Product product) {
        this.product = product;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getBatch() {
        return batch;
    }

    public void setBatch(String batch) {
        this.batch = batch;
    }

    public String getProductType() {
        return productType;
    }

    public void setProductType(String productType) {
        this.productType = productType;
    }

    public String getWeldName() {
        return weldName;
    }

    public void setWeldName(String weldName) {
        this.weldName = weldName;
    }

    public String getAssembleName() {
        return assembleName;
    }

    public void setAssembleName(String assembleName) {
        this.assembleName = assembleName;
    }

    public String getDebugName() {
        return debugName;
    }

    public void setDebugName(String debugName) {
        this.debugName = debugName;
    }

    public String getCheckName() {
        return checkName;
    }

    public void setCheckName(String checkName) {
        this.checkName = checkName;
    }

    public String getReason() {
        return reason;
    }

    public void setReason(String reason) {
        this.reason = reason;
    }
}
